import axios from 'axios';
import moment from 'moment';
import Router from '@koa/router';
import response from '../response.js';
import db from '../mysqlHelper.js';
import { uploadFile } from '../common/oss.js';
import fs from 'fs';


const BASE_URL = 'http://api.kgps.vip';
let token = '';
let expiredTime = moment();



async function login() {
    if (token && moment().isBefore(expiredTime)) {
        return true;
    }
    let url = `${BASE_URL}/user/login`;
    let data = {
        loginName: 'baotou535',
        password: 'baotou535'
    };
    try {
        let res = await axios.post(url, data);
        console.log(res.data);
        token = res.data.data.token;
        return true;
    } catch (error) {
        console.error('登陆出错', error.message);
    }
    return false;
}

async function getVehicleStatus(plateNos) {
    let loginRes = await login();
    if (!loginRes) {
        return;
    }
    let url = `${BASE_URL}/vehicle/status`;
    let headers = {
        token: token,
        'Content-Type': 'multipart/form-data'
    };
    let form = new FormData();
    form.append('plateNos', plateNos);

    try {
        let response = await axios.post(url, form, { headers: headers });
        console.log(response.data);
        if (response.data.status = true) {
            console.log('车辆状态:', response.data.data[0].status);
            return response.data.data[0];
        } else {
            console.log('获取车辆状态出错:', response.data.code);
            return { err: response.data.code };
        }
    } catch (error) {
        console.error('getVehicleStatus出错', error.message);
        return { err: error.message };
    }
}

/**
 * 获取车辆指定时间段的轨迹
 * @param {*} plateNos
 * @param {*} startTime
 * @param {*} endTime
 * @returns 
 */
async function getVehicelTrajectory(plateNo, startTime, endTime) {
    let loginRes = await login();
    if (!loginRes) {
        return;
    }
    let url = `${BASE_URL}/gps/search?plateNo=${plateNo}&startTime=${startTime}&endTime=${endTime}`;
    let headers = {
        token: token,
    };
    try {
        let response = await axios.get(url, { headers: headers });
        console.log(response.data);
        if (response.data.status = true) {
            console.log('车辆轨迹:', response.data.data);
            return response.data.data;
        } else {
            console.log('获取车辆轨迹出错:', response.data.code);
            return { err: response.data.code };
        }
    } catch (error) {
        console.error('getVehicelTrajectory出错', url, error.message);
        return { err: error.message };
    }
}

const router = new Router();
router.prefix('/api');

//获取车辆状态
router.post('/getVehicleStatus', async (ctx) => {
    let body = ctx.request.body;
    if (body.plateNos == null) {
        ctx.body = response.fail('缺少必填字段 plateNos');
        return;
    }
    let res = await getVehicleStatus(body.plateNos);
    if (res.err) {
        ctx.body = response.fail(res.err);
        return;
    }
    ctx.body = response.success(res);
});

//获取车辆轨迹
router.post('/getVehicelTrajectory', async (ctx) => {
    let body = ctx.request.body;
    if (body.plateNo == null) {
        ctx.body = response.fail('缺少必填字段 plateNo');
        return;
    }
    if (body.startTime == null) {
        ctx.body = response.fail('缺少必填字段 startTime');
        return;
    }
    if (body.endTime == null) {
        ctx.body = response.fail('缺少必填字段 endTime');
        return;
    }
    let res = await getVehicelTrajectory(body.plateNo, body.startTime, body.endTime);
    if (res.err) {
        ctx.body = response.fail(res.err);
        return;
    }
    ctx.body = response.success(res);
});

router.post('/enableVehicle/query', async (ctx) => {
    let body = ctx.request.body;
    if (body.plate == null) {
        ctx.body = response.fail('缺少必填字段 plate');
        return;
    }
    if (body.credit_code == null) {
        ctx.body = response.fail('缺少必填字段 场站信用代码');
        return;
    }
    let vehicle = await db.findOne('enable_vehicle', { plate: body.plate, receive_credit_code: body.credit_code });
    if (!vehicle) {
        ctx.body = response.fail('禁止通行');
        return;
    }
    let start_time = moment(vehicle.start_time);
    let end_time = moment(vehicle.end_time);
    let now = moment();
    if (now.isBetween(start_time, end_time, undefined, '[]')) {
        ctx.body = response.success({ transport_no: vehicle.no }, '允许通行');
    } else {
        ctx.body = response.success('禁止通行');
    }
});
//运单信息上报
router.post('/transport/report', async (ctx) => {
    const front_pic = ctx.request.files.front_pic; // 获取上传文件
    const top_pic = ctx.request.files.top_pic; // 获取上传文件    
    if (ctx.request.body.transport_no == null) {
        ctx.body = response.fail('缺少必填字段 transport_no');
        return;
    }
    let transport_no = ctx.request.body.transport_no;
    if (front_pic == null && top_pic == null) {
        ctx.body = response.fail('图片不允许为空');
        return;
    }
    let front_pic_path = '';
    let top_pic_path = '';
    let ossPath = `${transport_no}/${moment().format('YYYYMMDDHHmmss')}_front_pic.jpg`;
    let buffer = fs.readFileSync(front_pic.filepath);
    let result = await uploadFile(ossPath, buffer, 'public');
    if (result.code == 0) {
        ctx.body = response.fail(result.msg);
        return;
    } else {
        front_pic_path = result.url;
    }
    ossPath = `${transport_no}/${moment().format('YYYYMMDDHHmmss')}_top_pic.jpg`;
     buffer = fs.readFileSync(top_pic.filepath);
     result = await uploadFile(ossPath, buffer,  'public');
    if (result.code == 0) {
        ctx.body = response.fail(result.msg);
        return;
    } else {
        top_pic_path = result.url;
    }
    let  transport= await db.findOne('transport_record', { no: transport_no });
    if (transport == null) {
        ctx.body = response.fail('运单不存在');
        return;
    }
    let end_image = transport.end_image;
    if (end_image == null) {
        end_image = `${front_pic_path},${top_pic_path}`;
    } else {
        end_image = end_image + `${front_pic_path},${top_pic_path}`;
    }
    let res = await db.update('transport_record', { end_image: end_image }, { no: transport_no });
    if (res instanceof Error) {
        logger.error(`transport_record update error :` + res.message);
        ctx.body = response.fail(`transport_record update error :` + res.message);
        return;
    }

    ctx.body = response.success( '上报成功');

});



export { router };
